<?php

namespace AppApi\Controller;

use Think\Controller;

/**
 * App端Api初始化
 *
 * Class BaseController
 * @package ShopApi\Controller
 */
class BaseController extends Controller
{
    /**
     * 不需要校验密钥的Action
     *
     * @var array
     */
    protected $notCheckAction = [

    ];

    /**
     * 不需要登录的Action
     *
     * @var array
     */
    protected $notLoginAction = [

    ];

    /**
     * BaseController constructor.
     */
    public function __construct()
    {
        $data = $_SERVER['REQUEST_METHOD'] == 'POST' ? $_POST : $_GET;

        /* 校验基本参数，必须存在端口类型、版本号 */
        if (!in_array($data['port'], ['web', 'android', 'ios']) || empty($data['ver']))
        {
            showErrorMsg(10002);
        }

        /* 关键性接口需要校验密钥 */
        if (!in_array(ACTION_NAME, $this->notCheckAction))
        {
            $this->checkSecretKey($data);
        }

        if (!in_array(ACTION_NAME, $this->notLoginAction))
        {
            $this->checkLogin($data);
        }

        parent::__construct();
    }

    /**
     * 初始化
     */
    public function _initialize()
    {

    }

    /**
     * 校验数据
     *
     * @param $data
     * @return bool
     */
    private function checkSecretKey($data)
    {
        $authKey = '';

        if (isset($data['authKey']))
        {
            $authKey = $data['authKey'];
            unset($data['authKey']);
        }
        else
        {
            showErrorMsg(10001);
        }

        /* 时间戳校验 */
        if (isset($data['time']))
        {
            if (time() - $data['time'] > 30)
            {
                showErrorMsg(10046);
            }
        }
        else
        {
            showErrorMsg(10046);
        }

        ksort($data);
        $authKeyStr = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $authKeyStr = preg_replace('# #', '', $authKeyStr);
        $secretKey = C('SECRET_KEY');

        /* 加密串，验证数据统一性 */
        $authKeyCheck = md5($authKeyStr . $secretKey);

        if ($authKey != $authKeyCheck)
        {
            showErrorMsg(10001);
        }

        return TRUE;
    }


    /**
     * 校验登录
     *
     * @param $data
     * @return bool
     */
    private function checkLogin($data)
    {
        if (!isset($data['session_id']) || empty($data['session_id']))
        {
            showErrorMsg(10002);
        }

        if (empty(S("user_{$data['session_id']}")))
        {
            $userInfo = M('user')->where(['session_id' => $data['session_id']])->find();

            if (empty($userInfo))
            {
                showErrorMsg(10003);
            }

            S("user_{$data['session_id']}", $userInfo);
        }

        return TRUE;
    }

}